<template>
	<view class="container" :data-theme="theme">
		<view class="header">
			<!-- 商品状态 -->
			<tab-bar style="background-color: #FFF;" :tabList="tabList" :tabIndex.sync="currentIndex"
				@change="change"></tab-bar>
			<!-- <u-tabs :list="tabList" @click="click" style="display: flex;justify-content: center;" lineColor='#fe5c2d'
				:activeStyle="{
				    color: '#303133',
				    fontWeight: 'bold',
				    transform: 'scale(1.05)'
				}"></u-tabs> -->
			<!-- 日历 -->
			<!-- 		<view class="violation_time" v-if="isShowTime" @click="show = true">
				选择历史违规日期
			</view> -->

			<view class="violation_message_time" @click="show = true" v-if="isShowTime">
				<uni-datetime-picker v-model="range" type="daterange" @change="confirm" :color="bgColor">
					<view style="display: flex;justify-content: space-between;
			align-items: center;">
						<!-- <view class="violation_message_time" @click="show = true" v-if="isDay"> -->
						<view>{{params.beginTime}}</view>
						<view>至</view>
						<view>{{params.endTime }}</view>
						<view class="right_time">
							<view>共{{ violationDate }}天</view>
							<u-icon name="arrow-right" size="12"></u-icon>
						</view>
					</view>
				</uni-datetime-picker>
			</view>

			<!-- <u-calendar :show="show" :mode="mode" :min-date='calendar.minDate' :max-date="calendar.maxDate"
				:monthNum="calendar.monthNum" @confirm="confirm" color='#fe5c2d' :closeOnClickOverlay="true"
				@close="close"></u-calendar> -->
			<!-- 标签 -->
			<view class="violation_message_tag">
				<view class="message_tag" v-for="(tag, index) in tags" :key="index"
					:class="{'selected': selectedTag === index}" @click="changeTagColor(index)"> {{ tag }}
				</view>
				<view class="violation_message_tag_right" @click="toQuestion">
					<u-icon name="question-circle" style="margin-right: 2px;"></u-icon>
					<view>常见问题</view>
				</view>
			</view>
		</view>
		<view class="content">
			<!-- 这里是可滚动的内容 -->
			<scroll-view class="scroll-view" scroll-y @scrolltolower="scrollHandle">
				<view class="scroll-view-inner"> <!-- 内容区域 -->
					<!-- 今日违规内容 -->
					<view class="violation_content" v-for="(today, index) in violationList" :key="index"
						v-if="violationList.length > 0">
						<!-- 违规内容卡片 -->
						<view class="cause_content_card">

							<!-- 违规编号 -->
							<view class="violation_number">
								<view>违规编号：{{ today.breakRuleId }}</view>
								<view @click="openVisible(today,index)"> 评价</view>
							</view>
							<!-- 违规原因卡片 -->
							<view class="cause_content_top">
								<view class="cause_content_header">
									<view class="content_header_left">
										{{ today.title }}
									</view>
									<!-- <view class="content_header_right">
							无需申诉
						</view> -->
								</view>
								<view class="cause_content_body">
									<view class="content_list">
										<view class="cause_content_body_left">
											违规等级：
										</view>
										<view class="cause_content_body_right">
											{{ violationNature[Number(today.nature) - 1] }}
											<!-- 这个是字符串 -->
										</view>
									</view>
									<view class="content_list">
										<view class="cause_content_body_left">
											创建时间：
										</view>
										<view class="cause_content_body_right">
											{{ today.createTime }}
										</view>
									</view>
									<view class="content_list">
										<view class="cause_content_body_left">
											违规原因：
										</view>
										<view class="cause_content_body_right">
											<!-- 展示更多文字 -->
											<!-- <u-read-more :toggle="true" :showHeight="30"> -->
											<rich-text :nodes="today.reason"></rich-text>
											<!-- </u-read-more> -->
										</view>
									</view>
								</view>
							</view>
						</view>

						<view class="measure_content_card">
							<view class="measure_header">
								限权措施：{{ measureGrade[Number(today.grade) - 1] }}
							</view>
							<view class="measure_body">
								{{today.behaviour }}
							</view>
							<view class="measure_footer">
								<view class="measure_footer_list">
									<view>城市：<span>{{ today.city }}</span></view>
								</view>
								<view class="measure_footer_list">
									<view>SKU：<span>{{ today.sku }}</span></view>
								</view>
								<view class="measure_footer_list">
									<view>SKU名称：<span>{{ today.skuName }}</span></view>
								</view>
								<view>标签与实物不符-商品质量客诉量 {{ today.complain }}</view>
							</view>
						</view>

					</view>
					<!-- 没有违规内容 -->
					<view v-if="!violationList.length">
						<u-empty icon="http://cdn.uviewui.com/uview/empty/data.png">
						</u-empty>
					</view>
					<uni-load-more v-else :status="moreStatus"></uni-load-more>

					<!-- 弹出层 -->
					<view class="">
						<!-- <u-popup :show="visible" mode="bottom" @close="closeVisible" @open="openVisible" closeable
							round="15">
							<view class="card-box">
								<text class="title">满意度调查</text>
								<text class="text-c">请您对本条违规单做评价</text>
								<view class="meme">
									<u-rate activeIcon="heart-fill" :value="evaluateValue" size=30
										@change="changeEvaluate" inactiveIcon="heart"></u-rate>
								</view>
							</view>
						</u-popup> -->
						<tui-drawer mode="bottom" :visible="visible" @open="openVisible" @close="closeVisible">
							<view class="card-box" v-if="violationList.length > 0">
								<text @click="closeVisible" class="iconfont icon-guanbi5"></text>
								<text class="title">满意度调查</text>
								<text class="text-c"
									v-if="violationList[evaluateIndex].evaluateReadonly">您已评价，无需再次评价</text>
								<text class="text-c" v-else>请您对本条违规单做评价</text>
								<view class="meme">

									<uni-rate :activeColor="bgColor"
										:readonly="violationList[evaluateIndex].evaluateReadonly" size="39" margin="16"
										v-model="evaluateValue" @change="changeEvaluate" />
								</view>
							</view>
						</tui-drawer>
					</view>
				</view>

			</scroll-view>
		</view>
	</view>
</template>
<script>
	import tuiDrawer from '@/components/tui-drawer/index.vue';
	import tabBar from '@/components/tab-bar/tab-bar.vue';
	import {
		todayViolationApi,
		historyViolationApi,
		goEvaluate
	} from "@/api/violation.js";
	import {
		setThemeColor
	} from "../../../utils/setTheme";
	let app = getApp();
	export default {
		components: {
			tabBar,
			tuiDrawer
		},
		data() {
			return {
				bgColor: "#ffffff",
				theme: app.globalData.theme,
				tabList: [{ /// 头部选择
					name: "今日违规",
					// id: "tab11",
				}, {
					name: "历史违规",
					// id: "tab12",
				}],
				currentIndex: 0,
				isShowTime: false, // 判断是否展示日历标签
				show: false, // 日历展示
				mode: 'range', // 日期类型选择
				violationDate: '365', // 总共多少天
				isDay: false,
				// 改变标签样式
				tags: ['全部', '可申诉', '申诉中', '已申诉'],
				selectedTag: 0, // 默认选中第一个标签
				violationList: [], // 今日违规数据列表
				// 评价列表的index
				evaluateIndex: 0,
				//	弹出层控制
				visible: false,
				// 措施等级
				measureGrade: ['警告', '严重警告', '察看', '开除'],
				// 违规性质
				violationNature: ['一般违规', '较重违规', '重大违规'],
				// // APi-Params
				params: {
					// 申诉条件
					page: 1,
					limit: 20,
					day: '0',
				},
				beginTime: null, // 申诉开始时间
				endTime: null, // 申诉结束时间
				// 消息提示
				isNotifyShow: true,
				// 评分
				score: '',
				// 违规编号
				vioId: '',
				// //历史时间
				// calendar: {
				// 	minDate: '',
				// 	maxDate: '',
				// 	monthNum: 13,
				// },
				// 评价值
				evaluateValue: 1,
				// 是否只读评分
				evaluateReadonly: false,
				moreStatus: 'more', // 是否可以加载
				// -----
				range: [],
			}
		},
		onLoad(options) {
			this.bgColor = setThemeColor()
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.bgColor,
			});
			this.getTodayViolation();
		},

		created() {
			this.getDate()
		},
		methods: {
			// 滚动事件
			scrollHandle() {
				if (this.moreStatus == 'more') {
					this.params.page++
					this.getTodayViolation()
				}
			},
			// 获取今日时间
			getDate() {
				let today = new Date();
				let previousDate = new Date();
				previousDate.setFullYear(today.getFullYear() - 1)
				// 格式今年日期
				let year1 = today.getFullYear();
				let month1 = String(today.getMonth() + 1).padStart(2, '0');
				let day1 = String(today.getDate()).padStart(2, '0');
				// 格式去年日期
				let year2 = previousDate.getFullYear();
				let month2 = String(previousDate.getMonth() + 1).padStart(2, '0');
				let day2 = String(previousDate.getDate()).padStart(2, '0');
				// this.calendar.maxDate = year1 + '-' + month1 + '-' + day1;
				// this.calendar.minDate = year2 + '-' + month2 + '-' + day2;
				this.beginTime = year2 + '-' + month2 + '-' + day2;
				this.endTime = year1 + '-' + month1 + '-' + day2;
			},
			//	打开弹出层
			openVisible(item, index) {
				this.evaluateIndex = index
				if (item.evaluate != null && item.evaluate != '') {
					this.$set(this.violationList[index], 'evaluateReadonly', true)
					this.evaluateValue = item.evaluate
					uni.showToast({
						title: "您已评价",
						icon: 'none',
						duration: 1500
					})
				} else {
					this.evaluateValue = ""
					this.vioId = item.vioId
				}
				this.visible = true
			},
			//	关闭弹出层
			closeVisible() {
				this.visible = false
				this.messagesShow = true
			},
			// 处理标签样式
			changeTagColor(index) {
				this.selectedTag = index;
				if (index === 0) {
					delete this.params.appeal
				} else {
					this.params.appeal = index
				}

				this.getTodayViolation(true)
			},
			// 头部导航事件
			change(e) {
				this.click(e)
			},
			click(e) {
				if (e === 0) {
					this.isShowTime = false
					this.isDay = false
					this.selectedTag = 0;
					this.params.day = '0' // 今日违规
					delete this.params.appeal
					delete this.params.beginTime
					delete this.params.endTime
				} else {
					this.params.beginTime = this.beginTime
					this.params.endTime = this.endTime
					this.isShowTime = true
					this.selectedTag = 0;
					this.params.day = '1' // 取消今日违规
				}
				this.getTodayViolation(true)
			},
			// 去常见问题页面
			toQuestion() {
				uni.navigateTo({
					url: '/pages/violation/question/question',
				});
			},
			// 计算数组中任意日期的天数
			computedDate(dates) {
				// 将字符串日期转换为 Date 对象
				const date1 = new Date(dates[0]);
				const date2 = new Date(dates[1]);

				// 计算两个日期之间的毫秒数差值
				const timeDiff = Math.abs(date2.getTime() - date1.getTime());

				// 将毫秒数转换为天数
				this.violationDate = Math.ceil(timeDiff / (1000 * 3600 * 24));
			},
			// 获取日历信息
			confirm(e) {
				this.show = false
				this.params.beginTime = e[0]
				this.params.endTime = e[e.length - 1];
				// 调用计算天数的日期
				this.computedDate(e)
				this.isDay = true
				this.getTodayViolation(true)
			},
			// 关闭日历回调
			close() {
				this.show = false
			},

			// 改变评价
			async changeEvaluate(e) {
				this.score = e.value
				this.goEvaluate()
				// 判断是否评价
			},
			// 去评价  
			async goEvaluate() {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				try {
					let result = await goEvaluate({
						vioId: this.vioId,
						evaluate: this.score
					})
					if (result.code == 200) {
						if (result.data == 2) {
							this.getTodayViolation(true)
							this.visible = false
							uni.showToast({
								title: `评价成功${this.score}颗星`,
								icon: 'success',
								duration: 2000,
							})
						} else if (result.data == 1) {
							uni.showToast({
								title: '您已评价,不可再次评价',
								icon: 'none',
								duration: 2000,
							})
						}
					} else {
						uni.showToast({
							title: result.message,
							icon: 'none',
							duration: 2000
						})
					}
					setTimeout(() => {
						uni.hideLoading()
					}, 300)
				} catch (e) {
					setTimeout(() => {
						uni.hideLoading()
					}, 300)
					uni.showToast({
						title: e,
						icon: 'none',
						duration: 2000
					})
					//TODO handle the exception
					console.log(e)
				}
			},

			// 获取今日违规的功能模块
			async getTodayViolation(status) {
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				if (status) {
					this.violationList = []
					this.params.page = 1
					this.params.limit = 20
				}
				try {
					let result = await todayViolationApi(this.params)
					if (result.code == 200) {
						let items = result.data.list
						if (items.length > 0) {
							if (result.data.totalPage == this.params.page) {
								this.moreStatus = 'noMore'
							} else {
								this.moreStatus = 'more'
							}
							let data = items.map(item => {
								return {
									...item,
									evaluateReadonly: false
								}
							})
							console.log("this.violationList", this.violationList)
							this.violationList.push(...data)
						} else {
							this.moreStatus = 'noMore'
						}
					}
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					this.$util.Tips({
						title: e
					})
					//TODO handle the exception
					console.log(e)
				}
			},

		}
	}
</script>

<style lang="scss">
	page {
		height: 100%;


	}

	/* 标签 */
	::v-deep .u-tag--primary {
		width: 65px;
		justify-content: center;
		align-items: center;
		border: 0px;
		background-color: #f8f8f8;

		span {
			color: black;
			font-weight: bold;
		}
	}

	/* 违规内容 */
	::v-deep .u-empty {
		background-color: #f8f8f8;
		padding-top: 200px;
	}

	.selected {
		/* 设置选中标签的样式 */
		@include main_color(theme);
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.header {
		// height: 120px;
		background-color: #ffffff;

		.violation_message_time {
			padding: 20px;
			border-bottom: 1px solid #eee;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.right_time {
				display: flex;
			}
		}

		.violation_message_tag {
			margin: 20px;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.message_tag {
				background-color: #eee;
				padding: 5px 10px;
			}

			.violation_message_tag_right {
				display: flex;
				align-items: center;
			}
		}
	}

	.content {
		flex: 1;
		overflow: hidden;
	}

	.scroll-view {
		height: 100%;
	}

	.scroll-view-inner {

		/* 根据实际情况设置高度 */
		/* 违规内容 */
		.violation_content {
			margin: 10px;
			padding: 10px;
			background-color: #fff;
			border-radius: 6px;

			.cause_content_card {
				.violation_number {
					display: flex;
					justify-content: space-between;
					padding: 10px;
					border-bottom: 1px solid #eee;
				}

				.cause_content_top {
					padding: 10px;

					.cause_content_header {
						display: flex;
						justify-content: space-between;
						margin: 10px 0;

						.content_header_left {
							font-weight: bold;
							font-size: 16px;
						}
					}

					.cause_content_body {
						.content_list {
							display: flex;

							margin-top: 20px;

							.cause_content_body_left {
								flex-shrink: 0;
							}

							.cause_content_body_right {
								margin-left: 10px;
							}
						}
					}
				}
			}

			.measure_content_card {
				background-color: #f8f8f8;
				padding: 10px;
				border-radius: 5px;

				.measure_header {
					font-size: 16px;
					font-weight: bold;
				}

				.measure_body {
					padding: 10px 0;
					line-height: 18px;
				}

				.measure_footer {
					padding: 10px 0;

					.measure_footer_list {
						margin-bottom: 10px;

						span {
							font-weight: bold;
						}
					}
				}
			}
		}
	}

	/*	评价卡片 */
	.card-box {
		padding: 20px;
		border-top-left: 15px !important;
		border-top-right: 15px !important;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		color: #0d1b29;

		/* 头部标题 */
		.title {
			display: flex;
			justify-content: center;
			font-size: 18px;
			padding-bottom: 30px;
		}

		.text-c {
			font-size: 18px;
			font-weight: 600;
			padding-bottom: 40px;
		}

		/* 评价 */
		.meme {
			display: flex;

			justify-content: center;
		}
	}
</style>